<script setup lang="ts" name="ExcelExportDialog">
import draggable from 'vuedraggable'
import { DEF_FILE_NAME } from './helper'
import { cloneDeep } from 'lodash-es'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const visible = ref(false)

const props = defineProps({
  fieldList: { type: Array as any },
  filename: { type: String, default: () => DEF_FILE_NAME.split('.')[0] },
  hasSelected: { type: Boolean }
})

const newFilename = ref('')

// 打开弹窗
const open = (title: string | undefined) => {
  if (title) {
    exportInfo.value.filename = props.filename + '-' + title
  } else {
    exportInfo.value.filename = props.filename
  }
  visible.value = true
}
// 关闭弹窗
const close = () => {
  visible.value = false
}
// 子组件将方法暴露给父组件
defineExpose({ open })

const emit = defineEmits(['success'])

const handleOk = () => {
  if (checkedFields.value.length === 0 && exportInfo.value.headerType === 'custom') {
    message.error(t('export', 'emptyField'))
    return false
  }
  const sortArr: any = []
  const headerObj = {}
  if (checkedFields.value.length > 0) {
    fieldsList.value.forEach((item: any) => {
      if (checkedFields.value.includes(item.key)) {
        sortArr.push(item.key)
        headerObj[item.key] = item.value
      }
    })
  }
  emit('success', {
    filename: `${exportInfo.value.filename === '' ? newFilename.value : exportInfo.value.filename}.${exportInfo.value.fileType}`,
    fileType: exportInfo.value.fileType,
    dataScope: exportInfo.value.dataScope,
    header: headerObj,
    sort: sortArr,
    headerType: exportInfo.value.headerType
  })
  close()
}

const exportInfo = ref({
  filename: '',
  fileType: 'xlsx',
  dataScope: 1,
  headerType: 'default'
})

const checkAllField = ref(false)
const isIndeterminate = ref(false)
const checkedFields: any = ref([])
const fieldsList = ref(cloneDeep(props.fieldList) || [])

const headerTypeChange = () => {
  if (exportInfo.value.headerType === 'default') {
    fieldsList.value = cloneDeep(props.fieldList)
  }
}
const handleCheckAllChange = (val: boolean) => {
  checkedFields.value = []
  fieldsList.value.forEach((item) => {
    if (val) {
      checkedFields.value.push(item.key)
    }
  })
  isIndeterminate.value = false
  console.log(checkedFields.value)
}
const handleCheckedFieldsChange = (value: string[]) => {
  const checkedCount = value.length
  checkAllField.value = checkedCount === fieldsList.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < fieldsList.value.length
  console.log(checkedFields.value)
}
</script>

<template>
  <Dialog v-model="visible" width="600px" height="60vh" :title="t('export', 'title')" type="scroll">
    <ElForm>
      <ElFormItem :label="t('export', 'fileName')" prop="filename">
        <ElInput v-model="exportInfo.filename" clearable />
      </ElFormItem>
      <ElFormItem :label="t('export', 'fileType')">
        <ElSelect v-model="exportInfo.fileType" placeholder="">
          <ElOption :label="t('export', 'fileTypeXlsx')" value="xlsx" />
          <ElOption :label="t('export', 'fileTypeCsv')" value="csv" />
          <ElOption :label="t('export', 'fileTypeHtml')" value="html" />
          <ElOption :label="t('export', 'fileTypeXml')" value="xml" />
          <ElOption :label="t('export', 'fileTypeTxt')" value="txt" />
        </ElSelect>
      </ElFormItem>
      <ElFormItem :label="t('export', 'dataScope')">
        <ElSelect v-model="exportInfo.dataScope" placeholder="">
          <ElOption :label="t('export', 'dataScopeCurrentPage')" :value="1" />
          <ElOption :label="t('export', 'dataScopeSelected')" :value="2" :disabled="!props.hasSelected" />
          <ElOption :label="t('export', 'dataScopeAll')" :value="3" />
        </ElSelect>
      </ElFormItem>
      <ElFormItem :label="t('export', 'headerType')">
        <ElRadioGroup v-model="exportInfo.headerType" class="radio-button" @change="headerTypeChange">
          <ElRadioButton value="default">{{ t('export', 'headerTypeDefault') }}</ElRadioButton>
          <ElRadioButton value="custom">{{ t('export', 'headerTypeCustom') }}</ElRadioButton>
        </ElRadioGroup>
      </ElFormItem>
      <ElFormItem :label="t('export', 'fields')">
        <div class="field-list flex-1 m-6px">
          <div class="all-field">
            <ElCheckbox v-model="checkAllField" :indeterminate="isIndeterminate" :disabled="exportInfo.headerType === 'default'" @change="handleCheckAllChange">
              {{ t('export', 'allFields') }}
            </ElCheckbox>
          </div>
          <ElCheckboxGroup v-model="checkedFields" @change="handleCheckedFieldsChange">
            <draggable :list="fieldsList" :item-key="(key) => key" animation="300" :disabled="exportInfo.headerType === 'default'" handle=".move">
              <template #item="{ element }">
                <div class="item-field">
                  <span class="move"><svg-icon icon="ri:drag-move-2-fill" /></span>
                  <ElCheckbox :value="element.key" :disabled="exportInfo.headerType === 'default'">{{ element.value }}</ElCheckbox>
                </div>
              </template>
            </draggable>
          </ElCheckboxGroup>
        </div>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton @click="close">{{ t('action', 'cancel') }}</ElButton>
      <ElButton type="primary" @click="handleOk">{{ t('action', 'confirm') }}</ElButton>
    </template>
  </Dialog>
</template>

<style scoped lang="scss">

.field-list {
  border: 1px solid var(--el-border-color-lighter);

  .all-field {
    padding-left: 36px;
    background: var(--el-fill-color-light);
    border-bottom: 1px solid var(--el-border-color-lighter);
  }

  .el-checkbox-group {
    padding: 6px 0;
  }

  .item-field {
    display: flex;
    align-items: center;

    .move {
      padding: 0 10px;
      font-size: 14px;
      cursor: move;

      .el-icon {
        color: var(--el-text-color-secondary);
      }
    }
  }
}
</style>
